/*
 * comlan
 */

package com.promfy.bughunter.domain;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import com.promfy.bughunter.BugHunterActivity;
import com.promfy.bughunter.R;
import com.promfy.bughunter.db.DBService;
import com.promfy.bughunter.utils.DateFormatUtil;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.os.Handler;
import android.view.SurfaceHolder;

public class BugsContorl {
	private SurfaceHolder sfh;
	private Canvas canvas;
	private Context context;
	private KindPiaoChong kindPiaoChong;
	private int screenW;
	private int screenH;
	private List<CommonBug> bugList = new LinkedList<CommonBug>();
	private final static int WHOLE_BUGS_NUMBER = 10; 
	private final static int MIN_TOTAL_BUGS_NUMBER = 10; 
	private final static int MAX_TOTAL_BUGS_NUMBER = 15;
	private static final int MIN_DURATION_TIME_ADD_BUGS = 100 ; 
	private long lastAddBugs;
	private int pressedNumber; 
	private static final float EFFECTIVE_CIRCLE_ORIDUS = 50;
	private Handler handler;
	private ScoreBoard sb;
	private Leaves leaves;
	private Paint paint;
	private KindManager km;
	

	
	public BugsContorl(Context context, SurfaceHolder sfh, int screenW, int screenH) {
		this.context = context;
		this.sfh = sfh;
		this.screenH= screenH;
		this.screenW = screenW;
		

	}

	/**
	 * create all kinds of bugs,
	 * contains numbers, types, [positon]
	 * @param sfh 
	 */
	public void initBugs(){
		try {
			lastAddBugs = System.currentTimeMillis();
			canvas = sfh.lockCanvas();
			sb = new ScoreBoard(canvas, context, screenW, screenH);

//			cr = new CommonBug(context, canvas, screenW, screenH);
//			leaves = new Leaves(canvas, context, screenW, screenH);
//			cr.born(getRandomStartPoint(screenW, screenH));
//			bugList.add(cr);
//			kindPiaoChong = new KindPiaoChong(context, canvas, screenW, screenH);
//			kindPiaoChong.born(getRandomStartPoint(screenW, screenH));
//			bugList.add(kindPiaoChong);
//			bornBugs();
			km = new KindManager(context, canvas, screenW, screenH);
			bugList = km.createBugsRandom(WHOLE_BUGS_NUMBER);
			leaves = new Leaves(canvas, context, screenW, screenH);

//			bornBugs();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (canvas != null)
				sfh.unlockCanvasAndPost(canvas);
		}
	}
	
//	/**
//	 * born bugs.
//	 */
//	private void bornBugs(){
//		for(CommonBug cb : bugList){
//			cb.born(getRandomStartPoint(screenW, screenH));
//		}
//	}
	
	/**
	 * loop moving bugs.
	 */
	private int runBugs(){
		int size = bugList.size();
		CommonBug c;
		int num = 0;
		for(int i = size-1; i >= 0; i-- ){
			c = bugList.get(i);
			c.run();
			if(!c.isInScreen()){
				c.cancel();
				bugList.remove(c);
			}
			if(!c.isKilled()){
				num++;
			}
		}
		return num;
	}
	
	/**
	 * maintain numbers, if < MIN add bugs.
	 */
	public boolean maintainBugs(){
		int len = runBugs();
		leaves.runLeaves();
		boolean inTime = sb.runScoreBoardInTime();
		if(!inTime){
			DBService dbService = new DBService(context);
			Score score = new Score(DateFormatUtil.getCurrDate(),sb.getScore()+"");
			try {
				dbService.insert(score);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			//jump to GameResultsView
			((BugHunterActivity)context).onState(BugHunterActivity.STATUS_GAME_RESULTS);
			return false;
		}
	
//		if(!needAddBugs()) return;
		// check bugs number, and add if necessary.
//		int len = bugList.size();
		if(len < MIN_TOTAL_BUGS_NUMBER){
			addBugs();
		}
		return true;
	}
	
	/**
	 * check if need add bugs every MIN_DURATION_TIME_ADD_BUGS.
	 * @return
	 */
	private boolean needAddBugs() {
		if(System.currentTimeMillis() - lastAddBugs > MIN_DURATION_TIME_ADD_BUGS){
			lastAddBugs = System.currentTimeMillis();
			return true;
		}else{
			return false;
		}
	}

	/**
	 * check current number, add bugs randomly.
	 */
	private void addBugs(){
//		kindPiaoChong = (KindPiaoChong) new CommonBug(context, canvas, screenW, screenH);
//		kindPiaoChong.born(getRandomStartPoint(screenW, screenH));
//		bugList.add(kindPiaoChong);
		if(km != null){
			km.addBugRandom();
		}
		//KindManager.getInstance(context, canvas, screenW, screenH).addBugRandom();
	}
	


	/**
	 * check if it is any bug pressed.
	 * @param lastX
	 * @param lastY
	 */
	public void anyBugPressed(float lastX, float lastY) {
		sb.setPressedNumber(0);
		for(CommonBug cb : bugList){
			if(inInEffectiveCircle(lastX, lastY, cb.getCurPoint(), cb.getIcons())){
				cb.setPressed(true);
				sb.addScore(cb.getScoreValue());
				sb.addPressedNumeber();
			}
		}
		if(sb.getPressedNumber() < 2) return;
		if(sb.getPressedNumber() == 2){
			sb.setGoodScore(5);
//			sb.showGood();
		}else if(sb.getPressedNumber()== 3){
			sb.setGoodScore(10);
//			sb.showExcellent();
		}else if(sb.getPressedNumber() > 3){
			sb.setGoodScore((sb.getPressedNumber()-1)* 5);
//			sb.showPerfect();
		}
		sb.setIndex(0);
		
	}
	
	/**
	 * check if it is in effective circle.
	 * @param lastX
	 * @param lastY
	 * @param p
	 * @return
	 */
	private boolean inInEffectiveCircle(float lastX, float lastY, PointF p, Bitmap[] icons){
		int w = icons[0].getWidth();
		int h = icons[0].getHeight();
		int mSize = (h+w)/3;
		if(((lastY - p.y) * (lastY - p.y) + (lastX - p.x) * (lastX - p.x))
				< mSize * mSize){
			return true;
		}else{
			return false;
		}
	}

	public void cancelPressedBug() {
		for (final CommonBug cb : bugList) {
			if (cb.isPressed()) {
				cb.setKilled(true);
			}
		}
	}

}
